//
//  TicTacViewController.m
//  TicTacToe
//
//  Created by Tim on 09-11-22.
//  Copyright 2009 Tim Dimsdale. All rights reserved.
//
// This file is part of TicTacToe.
// 
// TicTacToe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// TicTacToe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with TicTacToe.  If not, see <http://www.gnu.org/licenses/>
//
#import "TicTacView.h"



@implementation TicTacView

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
		myGrid = [[TicTacGrid alloc]init];  
		isActive = false;

    }
    return self;
}

-(void) dealloc
{
	[myGrid release];
	[super dealloc];
}



- (void)setIsActive:(bool)active {
	isActive = active;
}

- (void)newGame 
{

	[self setNeedsDisplay: YES];
	isActive = true;
}

- (void)setModel: (TicTacModel*)model;
{
	ticTacModel=model;
}

- (void)drawRect:(NSRect)rect {
	[ticTacModel debugDumpModel];
	[myGrid drawGrid:rect withModel:ticTacModel enabled:isActive];
}

- (BOOL)isFlipped {
	return TRUE;
}



// we accept first responder status.  This is necessary to receive
// mouse motion events

- (BOOL) acceptsFirstResponder
{
    return (YES);
	
} // acceptsFirstResponder

-(void)rightMouseDown:(NSEvent *) event {
	[self dealWithHuman:event];

}

- (void)mouseDown:(NSEvent *)event {
		[self dealWithHuman:event];
}

- (void)dealWithHuman:(NSEvent*)event {
	if ( !isActive)
		return;
	
    NSPoint mouse;
    mouse = [self convertPoint: [event locationInWindow]  fromView: nil];	
	TicTacPosition* playingPosition = [self gridIndexAtPoint:mouse];
	
	//NSLog(@"Click at x:%d y:%d", [playingPosition getX], [playingPosition getY] );
	[[NSNotificationCenter defaultCenter]postNotificationName:HumanPerformedEventNotification object:playingPosition];
}

- (void)updateDisplay {
	[self setNeedsDisplay:YES];
}

/*
- (void) mouseMoved: (NSEvent *) event
{
// get the mouse position in view coordinates
//    NSPoint mouse;
//    mouse = [self convertPoint: [event locationInWindow]  fromView: nil];

} // mouseMoved
*/


- (TicTacPosition*) gridIndexAtPoint : (NSPoint) point
{
	NSRect frame = [self bounds];
	int eachCellWidth = frame.size.width / 3;
	int eachCellHeight = frame.size.height / 3;

	TicTacPosition* gridPosition = [[TicTacPosition alloc]initWithX:((int)(point.x / eachCellWidth)) andY:((int)(point.y / eachCellHeight))];
	return gridPosition;
}

@end
